import re


def get_gender_from_id(id_number):
    """
    根据身份证号码获取性别
    :param id_number: 身份证号码
    :return: 性别 ('男' 或 '女')
    """
    # 检查身份证号是否有效
    id_number = id_number.strip("'")
    if not id_number or len(id_number) < 17:
        return None

    # 第17位数字用于表示性别，奇数为男，偶数为女
    gender_digit = int(id_number[16])

    if gender_digit % 2 == 1:
        return '男'
    else:
        return '女'
def group_2(tree):
    dict_group_2 = {"姓名": "", "拼音检索": "", "性别": "", "出生日期": "", "证件类型": "", "身份证号": "", "年龄": "", "特殊人群分类": "",
                    "人群分类": "", "国籍": "", "籍贯": "", "常驻类型": "", "户籍地址": "", "户别": "", "暂住证": "", "来京日期": "", "民族": "",
                    "婚姻状况": "", "市": "", "区/县": "", "乡镇/街道": "", "居委会/村": "", "小区": "", "门牌号": "", "文化程度": "",
                    "户口所在地-市": "", "户口所在地-区": "", "户口所在地-街": "", "户口所在地": "", "现住址": "", "现住址详细地址": "", "所属派出所": "",
                    "邮政编码": None,
                    "EMail": None, "住宅电话": "", "本人电话": "", "联系人姓名": "", "联系人电话": "", "职业": "", "工作单位": "", "单位电话": "",
                    "单位联系人姓名": "", "单位联系人电话": "", "医疗费用支付方式": "", "农合号": "", "医保号": "", "医疗支付方式其它": "", "定点医疗单位": "",
                    "居住状况": "", "同住者": ""}
    list_xing = ["未知的性别", "男", "女", "未说明的性别"]
    list_zheng = ["二代身份证", "军官证/士兵证", "护照", "其他", "台湾居民来往大陆通行证", "港澳居民来往内地通行证"]
    list_renqun = ["低保", "特困", "医保签约", "持慈善卡", "离退休局级干部", "非典治愈病人", "孤寡", "空巢", "其他", "低收入", "计划生育特殊家庭"]
    dict_group_2["姓名"] = tree.xpath('//input[@id="personName"]/@value')[0]
    dict_group_2["拼音检索"] = tree.xpath('//input[@id="nameIndex"]/@value')[0]


    print(dict_group_2["性别"])
    dict_group_2["出生日期"] = tree.xpath('//input[@name="EHRBASE.birthDate"]/@value')[0]
    dict_group_2["证件类型"] = list_zheng[
        int(tree.xpath('//input[@name="EHRDETAILS.idType" and @checked="checked"]/@value')[0]) - 1]
    dict_group_2["身份证号"] = "'"+str(tree.xpath('//input[@name="EHRBASE.idNumber"]/@value')[0]).strip()

    try:
        sex = int(tree.xpath('//input[@name="EHRBASE.gender"and@checked="checked"]/@value')[0])
        if sex == 9:
            gender = get_gender_from_id(dict_group_2["身份证号"])
            dict_group_2["性别"] = gender
        else:
            dict_group_2["性别"] = list_xing[int(tree.xpath('//input[@name="EHRBASE.gender"and@checked="checked"]/@value')[0])]
    except:
        gender = get_gender_from_id(dict_group_2["身份证号"])
        dict_group_2["性别"] = gender

    dict_group_2["年龄"] = tree.xpath('//*[@id="age"]/@value')[0]
    try:
        list_fenlei = []
        list_teshurenqunfenlei = tree.xpath('//input[@name="EHRBASE.specialPeopleValue"and@checked="checked"]/@value')
        for i in list_teshurenqunfenlei:
            fenlei = list_renqun[int(i) - 1]
            list_fenlei.append(fenlei)
        dict_group_2["特殊人群分类"] = "，".join(list_fenlei)
    except:
        dict_group_2["特殊人群分类"] = "无"
    if dict_group_2["特殊人群分类"] =="":
        dict_group_2["特殊人群分类"] = "无"

    all_renqunfenlei = tree.xpath('//*[@id="ehrForm"]/div[8]/input[@checked="checked"]')
    all_renqun = []
    for i in all_renqunfenlei:
        renqun_dan = i.xpath('./following-sibling::span[1]/label/text()')[0]
        all_renqun.append(renqun_dan)

    dict_group_2["人群分类"] = "，".join(all_renqun)
    if dict_group_2["人群分类"] == "":
        dict_group_2["人群分类"] = "无"

    selected_nationality = tree.xpath(
        '//input[@name="EHRDETAILS.nationality" and @checked]/following-sibling::span[1]/label/text()')
    if selected_nationality:
        dict_group_2["国籍"] = selected_nationality[0]
    else:
        dict_group_2["国籍"] = None
    if dict_group_2["国籍"] == "其他":
        other_country = tree.xpath('//input[@id="nationalityDescription"]/@value')
        if other_country and other_country[0].strip():
            try:
                dict_group_2["国籍"] = other_country[0]
            except:
                dict_group_2["国籍"] = None
    try:
        dict_group_2["籍贯"] = tree.xpath('//input[@id="EHRDETAILS.nativePlace"]/@value')[0]
    except:
        dict_group_2["籍贯"] = None




    # 获取被选择的常住类型一行
    changzhu = tree.xpath('//input[@name="EHRBASE.householdType" and @checked]/@value')[0]
    if changzhu == '1':
        dict_group_2["常驻类型"] = "户籍"
    elif changzhu == '2':
        dict_group_2["常驻类型"] = "非户籍"
    else:
        dict_group_2["常驻类型"] = "不详"
    hometown = tree.xpath('//input[@id="hometown"]/@value')
    if hometown:
        dict_group_2["户籍地址"] = hometown[0]
    else:
        dict_group_2["户籍地址"] = None
    try:
        hubie = tree.xpath('//input[@name="EHRBASE.accountType" and @checked]/@value')[0]

        if hubie == '1':
            dict_group_2["户别"] = "农业"
        elif hubie == '2':
            dict_group_2["户别"] = "非农业"
        else:
            dict_group_2["户别"] = "不详"
    except:
        dict_group_2["户别"] = None

    selected_radio = tree.xpath('//input[@name="EHRDETAILS.tempLicence" and @checked]/@value')
    if selected_radio:
        temp_licence_value = selected_radio[0]
        temp_licence_map = {
            "1": "无",
            "2": "A类",
            "3": "B类"
        }
        dict_group_2["暂住证"] = temp_licence_map.get(temp_licence_value, "未录入")

    else:
        dict_group_2["暂住证"] = None

    date_arriving = tree.xpath('//input[@id="dateArriving"]/@value')
    if date_arriving and date_arriving[0]:
        dict_group_2["来京日期"] = date_arriving[0]
    else:
        dict_group_2["来京日期"] = None

    list_minzu = ["汉族", "蒙族", "回族", "藏族", "苗族", "满族", "壮族", "不详", "其他"]
    try:
        dict_group_2["民族"] = list_minzu[
            int(tree.xpath('//input[@name="EHRDETAILS.ethnicType" and @checked="checked"]/@value')[0]) - 1]
        if dict_group_2["民族"] == "其他":
            dict_group_2["民族"] = tree.xpath('//input[@name="EHRDETAILS.ethnicOther"]/@value')[0]
    except:
        dict_group_2["民族"] = None
    list_hunyinzhuangkuang = ["未婚", "已婚", "丧偶", "离婚", "未说明"]
    try:
        dict_group_2["婚姻状况"] = list_hunyinzhuangkuang[
            int(tree.xpath('//input[@name="EHRDETAILS.maritalStatus"and @checked="checked"]/@value')[0]) - 1]
    except:
        dict_group_2["婚姻状况"] = None
    try:
        list_wenhua = ["研究生及以上学历", "大学本科", "大学专科及以上", "中等专业学校或中等技术学校", "技工学校", "高中/技校/中专", "初中", "小学", "文盲及半文盲", "不详",
                       "学龄前"]
        dict_group_2["文化程度"] = \
        tree.xpath('//input[@name="EHRDETAILS.educationLevel" and @checked="checked"]/parent::label/text()')[0]
    except:
        dict_group_2["文化程度"] = None


    try:
        dict_group_2["户口所在地-市"] = tree.xpath('//select[@id="regCity"]/option[@selected]/text()')[0]
    except:
        dict_group_2["户口所在地-市"] = "无"
    # 市
    dict_group_2["市"] = "北京市"

    try:
        dict_group_2["户口所在地-区"] = tree.xpath('//select[@id="regDistrict1"]/option[@selected]/text()')[0]
    except:
        dict_group_2["户口所在地-区"] = "无"
    try:
        dict_group_2["户口所在地-街"] = tree.xpath('//input[@id="regDetail"]/@value')[0]
        if dict_group_2["户口所在地-街"] == "":
            dict_group_2["户口所在地-街"] = "无"
    except:
        dict_group_2["户口所在地-街"] = "无"
    list_hukousuozaidi = [dict_group_2["户口所在地-市"], dict_group_2["户口所在地-区"], dict_group_2["户口所在地-街"]]
    dict_group_2["户口所在地"] = "|".join(list_hukousuozaidi)

    # 获取现住址
    script_text = tree.xpath('//script[contains(., "addrDistrictName")]/text()')[0]

    # 正则提取变量值
    addr_district_name = re.search(r"addrDistrictName\s*=\s*'([^']*)'", script_text).group(1)
    if addr_district_name == "":
        addr_district_name = "无"
    dict_group_2["区/县"] = addr_district_name
    addr_street_name = re.search(r"addrStreetName\s*=\s*'([^']*)'", script_text).group(1)
    if addr_street_name == "":
        addr_street_name = "无"
    dict_group_2["乡镇/街道"] = addr_street_name
    addr_committee_name = re.search(r"addrCommitteeName\s*=\s*'([^']*)'", script_text).group(1)
    if addr_committee_name == "":
        addr_committee_name = "无"
    dict_group_2["居委会/村"] = addr_committee_name
    addr_area_name = re.search(r"addrAreaName\s*=\s*'([^']*)'", script_text).group(1)
    if addr_area_name == "":
        addr_area_name = "无"
    dict_group_2["小区"] = addr_area_name
    address_name = re.search(r"addressName\s*=\s*'([^']*)'", script_text).group(1)
    if address_name == "":
        address_name = "无"
    dict_group_2["门牌号"] = address_name
    address_info = [addr_district_name, addr_street_name, addr_committee_name, addr_area_name, address_name]
    address_info_end = ["无" if item == "" else item for item in address_info]
    dict_group_2["现住址"] = address_info_end

    dict_group_2["现住址详细地址"] = tree.xpath('//*[@id="curAddress"]/@value')[0]

    # div[17]所属派出所
    all_td = tree.xpath('//*[@id="ehrForm"]/div[17]//td')
    for i in all_td:
        try:
            key = i.xpath('.//span/text()')[0]
            key = key.strip("：")
            value = i.xpath(".//input/@value")[0]
            dict_group_2[key] = value
        except IndexError:
            dict_group_2[key] = None

    # Email
    try:
        dict_group_2["EMail"] = tree.xpath('//input[@id="EHRDETAILS.EMail"]/@value')[0]
    except:
        dict_group_2["EMail"] = None

    benrendianhua = dict_group_2["手机"]

    dict_group_2["本人电话"] = "'"+str(benrendianhua)
    del dict_group_2["手机"]

    # 职业div[18]
    selected_profession = tree.xpath(
        '//input[@name="EHRDETAILS.professionType" and @checked]/following-sibling::span[1]/label/text()')
    # 如果有选中的职业，则赋值给 dict_group_2["职业"]，否则设为 "无"
    if selected_profession:
        dict_group_2["职业"] = selected_profession[0]
    else:
        dict_group_2["职业"] = "无"

    # 疾病div[19]
    all_span = tree.xpath('//*[@id="ehrForm"]/div[19]//span')
    all_input = tree.xpath('//*[@id="ehrForm"]/div[19]//input')
    for i in range(len(all_span)):
        try:
            key = all_span[i].text
            key = key.strip("：")
            value = all_input[i].get('value')
            dict_group_2[key] = value
        except:
            dict_group_2[key] = None



    # 费用支付方式div[20]
    all_input_xuanzhong = tree.xpath('//*[@id="ehrForm"]/div[20]//input[@checked="checked"]')
    list_feiyong = []
    for input_element in all_input_xuanzhong:
        label_text = input_element.xpath("./following-sibling::span[1]/label")[0].text
        list_feiyong.append(label_text)
    list_feiyong = "，".join(list_feiyong)
    dict_group_2["医疗费用支付方式"] = list_feiyong
    if dict_group_2["医疗费用支付方式"] == "":
        dict_group_2["医疗费用支付方式"] = None

    nonghehao = tree.xpath('//*[@id="ehrForm"]/div[20]//input[@class="input_bottomLine_text_span"]')[1]
    nonghehao_value = nonghehao.get('value')
    if nonghehao_value:
        dict_group_2["农合号"] = "'"+str(nonghehao_value)
    else:
        dict_group_2["农合号"] = None
    if dict_group_2["农合号"] == "'None":
        dict_group_2["农合号"] = None

    yibaohao = tree.xpath('//*[@id="insuranceNumber"]')[0]
    yibao_value = yibaohao.get('value')
    if yibao_value:
        dict_group_2["医保号"] = yibao_value
    else:
        dict_group_2["医保号"] = None
    dict_group_2["医保号"] = "'"+str(dict_group_2["医保号"])
    if dict_group_2["医保号"] == "'None":
        dict_group_2["医保号"] = None

    qitazhifufangshi = tree.xpath('//*[@id="ehrForm"]/div[20]//input[@name="EHRDETAILS.payTypeDescription"]/@value')[0]
    if qitazhifufangshi == "":
        dict_group_2["医疗支付方式其它"] = None
    else:
        dict_group_2["医疗支付方式其它"] = qitazhifufangshi

    # 定点医疗单位div[21]
    dingdianyiliaodanwei = tree.xpath('//*[@id="ehrForm"]/div[21]//input')
    list_yiliaodanwei = []
    for i in dingdianyiliaodanwei:
        value = i.get("value")

        if i.get("value") == None:
            value = "无"
        if i.get("value")=="":
            value = "无"
        list_yiliaodanwei.append(value)
    dict_group_2["定点医疗单位"] = ",".join(list_yiliaodanwei)


    # 居住状况div[22]
    try:
        all_input = tree.xpath('//*[@id="ehrForm"]/div[22]//input[@checked="checked"]')[0]
        input = all_input.xpath('following-sibling::text()[1]')[0]
        dict_group_2["居住状况"] = input
    except:
        dict_group_2["居住状况"] = "无"

    # 同住者div[23]
    all_inputs = tree.xpath('//input[@name="EHRDETAILS.inmate" and @checked="checked"]')
    list_tongzhu = []
    for i in all_inputs:
        input = i.xpath('following-sibling::text()[1]')[0]
        list_tongzhu.append(input)
    tongzhuzhe = "，".join(list_tongzhu)

    dict_group_2["同住者"] = tongzhuzhe
    if dict_group_2["同住者"] == '':
        dict_group_2["同住者"] = "无"
    dict_group_2["联系人电话"]==str(dict_group_2["联系人电话"])
    if dict_group_2["联系人电话"] == "":
        dict_group_2["联系人电话"] = None
    if dict_group_2["联系人姓名"]=="" :
        dict_group_2["联系人姓名"] = None
    if dict_group_2["单位联系人电话"]!="不祥" :
        dict_group_2["单位联系人电话"] = str(dict_group_2["单位联系人电话"])
    if dict_group_2["单位联系人电话"]=="" :
        dict_group_2["单位联系人电话"] = None
    print("问题不在2")
    return dict_group_2


